/*
 * EditMinistry.java
 * This class will allow the user to Edit an
 * active ministry in the database.
 */

package gui;
import db.DBManager;
import struct.*;
import javax.swing.*;
import java.util.*;

/**
 *
 * @author Sarah Wegner & Gabrielle DuBois
 */
public class EditMinistry extends javax.swing.JFrame {

    /*Variables*/
    //ministry has 4 components
    String[] originalMinistry = new String[4];

    /** Creates new form EditMinistry */
    public EditMinistry(String[] ministryInfo) {
        initComponents();
        initFields(ministryInfo);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        rbNo = new javax.swing.JRadioButton();
        rbYes = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtNotes = new javax.swing.JTextArea();
        lblAddNewHousehold = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        btCancel = new javax.swing.JButton();
        txtMinistryName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        btSave = new javax.swing.JButton();
        chkDeactivate = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        buttonGroup1.add(rbNo);
        rbNo.setText("No");

        buttonGroup1.add(rbYes);
        rbYes.setText("Yes");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Ministry Name:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Is this ministry a Community Service Ministry?");

        txtNotes.setColumns(20);
        txtNotes.setRows(5);
        jScrollPane1.setViewportView(txtNotes);

        lblAddNewHousehold.setFont(new java.awt.Font("Tahoma", 0, 14));
        lblAddNewHousehold.setText("Edit Ministry");

        jSeparator2.setForeground(new java.awt.Color(0, 153, 0));

        btCancel.setText("Cancel");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        txtMinistryName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMinistryNameActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Notes:");

        btSave.setText("Save");
        btSave.setMaximumSize(new java.awt.Dimension(65, 23));
        btSave.setMinimumSize(new java.awt.Dimension(65, 23));
        btSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveActionPerformed(evt);
            }
        });

        chkDeactivate.setText("Deactivate?");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblAddNewHousehold)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(29, 29, 29)
                            .addComponent(rbYes, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
                            .addGap(102, 102, 102)
                            .addComponent(rbNo, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(18, 18, 18)
                            .addComponent(txtMinistryName, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(41, 41, 41)
                            .addComponent(jLabel3)
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(chkDeactivate)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE)
                                    .addComponent(btCancel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(btSave, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)))))
                .addGap(23, 23, 23))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblAddNewHousehold)
                .addGap(11, 11, 11)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
                    .addComponent(txtMinistryName))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(rbYes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(rbNo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(101, 101, 101))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btSave, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btCancel)
                    .addComponent(chkDeactivate))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtMinistryNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMinistryNameActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_txtMinistryNameActionPerformed

    private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed
        boolean saveMinistry = false;

        //Check Required fields
        if(txtMinistryName.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Please complete " +
                    "the required fields for a ministry before saving.",
                    "Required Fields", JOptionPane.WARNING_MESSAGE);
            saveMinistry = false;
        }//if
        else{
            saveMinistry = true;
            save();
        }//else

    }//GEN-LAST:event_btSaveActionPerformed

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        int answer = JOptionPane.showConfirmDialog(null, "Are you sure "+
                "you would like to close "+ "\n"+ "this window without saving?",
                "Cancel", JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            // User clicked YES.
            this.dispose();
        } //else if (answer == JOptionPane.NO_OPTION)
         // User clicked NO. Do nothing.
    }//GEN-LAST:event_btCancelActionPerformed

    /**
     * Method to initialize fields to editing
     * records values
     */
    public void initFields(String[] ministryInfo){
        //get Ministry Name from main gui
        txtMinistryName.setText(ministryInfo[0]);

        //get if ministry is community service
        if(ministryInfo[1].equals("true")){
            rbYes.setSelected(true);
        }
        else{
            rbNo.setSelected(true);
        }

        //ministryInfo[2] = isActive; we don't need to check for this.

        //get if ministry has notes
        txtNotes.setText(ministryInfo[2]);

        originalMinistry = ministryInfo;
    }//initFields()

   /**
     * Method to save all fields to the database.
     * Called when a user clicks the "Save" button.
     */
    public void save(){
        boolean doesExist = false;
        boolean saveSuccessful = false;
        boolean editMinistry = true;
        boolean isActivated;
        boolean deactivateMinistry = true;
        boolean communityService;
        String[] ministryKey = {txtMinistryName.getText()};

        //is the edited ministry active?
        if(chkDeactivate.isSelected()){
            isActivated = false;
        }//if
        else{
            isActivated = true;
        }//else
        //is the edited ministry a community service?
        if(rbYes.isSelected()){
            communityService = true;
        }//if
        else{
            communityService = false;
        }//else

        //Save edited ministry to the database
        try{
            DBManager dbManager = new DBManager();

            //Check if this edited name exists in Database ONLY if it is not
            //equal to the original name
            if(!originalMinistry[0].equals(ministryKey[0])){
                doesExist = dbManager.doesExist("ministries", ministryKey);
            }//if
            if(!doesExist){
                //update ministry information
                editMinistry = dbManager.editMinistry(originalMinistry[0],
                                txtMinistryName.getText(),
                                communityService,
                                txtNotes.getText());
                //if the ministry is now deactivated, call to set new ministry name as deactivated
                deactivateMinistry =
                        dbManager.toggleMinistryActivationStatus(txtMinistryName.getText(), isActivated);
           }//if
           else{
             JOptionPane.showMessageDialog(null, "The ministry name you entered"
                     + " already exists. Please enter a different name." + "\n"
                     + "Note: Check the status of this ministry. If it is deactivated,"
                     + "\n" +
                       " go to the 'Reactivate Ministry Window' to reactivate it.",
                "Database Error", JOptionPane.WARNING_MESSAGE);
             return;
           }//else

            if(editMinistry && deactivateMinistry){
                saveSuccessful = true;
            }//if
            else{
                saveSuccessful = false;
            }//else
        }//try
        catch(Exception ex){
            saveSuccessful = false;
            JOptionPane.showMessageDialog(null, "Error with St Patrick database." + "\n" +
                    "Please contact your Database Administrator, a.k.a Thomas Naps, for help.",
                    "Database Error", JOptionPane.ERROR_MESSAGE);
        }//catch

        //Depending on results of save to database, clear and confirm save
        //or give error message
        if(saveSuccessful == true){
            JOptionPane.showMessageDialog(null,"Save successful!", "Save",
                    JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
            
        }//if
        else{
            JOptionPane.showMessageDialog(null, "Error with saving"+
                    " information to database.", "Save Error",
                    JOptionPane.ERROR_MESSAGE);
        }//else
    }//save

    /**
    * Makes the Edit Ministry window visible.
    */
    public static void run(String[] ministryInfo) {
        new EditMinistry(ministryInfo).setVisible(true);
    }//run

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btSave;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JCheckBox chkDeactivate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblAddNewHousehold;
    private javax.swing.JRadioButton rbNo;
    private javax.swing.JRadioButton rbYes;
    private javax.swing.JTextField txtMinistryName;
    private javax.swing.JTextArea txtNotes;
    // End of variables declaration//GEN-END:variables

}
